<?php

namespace app\api\controller;

use app\facade\Redis;
use think\Validate;
use app\facade\Mns;
use app\models\{Recpeople, Region, PlatClass, PlatSons, Banner, Goods, Business, GoodsSpec, BusinessArea, Compent, UserLevel, Wechat, Config, ConvenClass, Conven, Agent};
use think\facade\Env;
use think\Db;
use oss\Oss;
use think\db\Where;
use EasyWeChat\Factory;


class Other extends Base
{

    public function getptdatas()
    {
        $ptdatas = (new Config())->where('name', 'ptdatas')->value('value');
        $ptdatas = json_decode($ptdatas, true);
        if (!empty($ptdatas['orderuser'])) {
            unset($ptdatas['orderuser']);
        }
        $ptdatas['userlists'] = [];
        $lists = Redis::lRange('ptdatas_lists', 0, 30);
        foreach ($lists as $list) {
            $ptdatas['userlists'][] = unserialize($list);
        }
        $this->result($ptdatas, 0, '获取成功');
    }

    public function getopenid()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require',
            'state' => 'require'
        ], [
            'id.require' => 'ID不能为空',
            'state.require' => '类型必须填写',
        ]);
        if (!$validate->check($data)) {
            $results = ['status' => 1, 'info' => $validate->getError()];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (empty($wxuser['id'])) {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
            if ($data['state'] == 1) {
                $business = (new Business())->where('id', $data['id'])->find();
                if (empty($business)) {
                    $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
                    return view(null, ['list' => $results]);
                }
                if (!empty($business['openid'])) {
                    $results = ['status' => 1, 'info' => '授权失败,请先解绑授权'];
                    return view(null, ['list' => $results]);
                }
                if ($business['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
                    return view(null, ['list' => $results]);
                }
                $res = (new Business())->where('id', $data['id'])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败,请重试'];
                    return view(null, ['list' => $results]);
                }
            } elseif ($data['state'] == 2) {
                $business = (new Agent())->where('id', $data['id'])->find();
                if (empty($business)) {
                    $results = ['status' => 1, 'info' => '授权失败,商家不存在'];
                    return view(null, ['list' => $results]);
                }
                if (!empty($business['openid'])) {
                    $results = ['status' => 1, 'info' => '授权失败,请先解绑授权'];
                    return view(null, ['list' => $results]);
                }
                if ($business['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
                    return view(null, ['list' => $results]);
                }
                $res = (new Agent())->where('id', $data['id'])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败,请重试'];
                    return view(null, ['list' => $results]);
                }
            } else {
                $results = ['status' => 1, 'info' => '授权失败,请重试'];
                return view(null, ['list' => $results]);
            }
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => '授权失败,请重试'];
            return view(null, ['list' => $results]);
        }
        $message = [
            '测试信息', 123456789, '测试信息', 100, date('Y-m-d H:i:s')
        ];
        $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【信息通知】');
        $results = ['status' => 0, 'info' => '授权成功，您已订阅公众号订单通知服务!'];
        return view(null, ['list' => $results]);
    }


    public function getOpenIds()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'code' => 'require',
            'mobile' => 'require'
        ], [
            'code.require' => 'code不能为空',
            'mobile.require' => '师傅端手机号不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Recpeople())->where(['mobile' => $data['mobile']])->find();
        $results = ['status' => 1, 'info' => '授权失败!'];
        if (empty($user)) {
            $results = ['status' => 1, 'info' => '账号不存在,请确保手机号码正确!'];
            return view(null, ['list' => $results]);
        }
        $config = config('wechat2.');
        $message = [
            '测试信息', 123456789, '测试信息', 100, date('Y-m-d H:i:s')
        ];
        try {
            $app = Factory::officialAccount($config);
            $wxuser = $app->oauth->user();
            if (!empty($wxuser['id'])) {
                if (!empty($user['openid']) && $user['openid'] == $wxuser['id']) {
                    $results = ['status' => 0, 'info' => '公众号订单通知服务订阅成功!(授权成功公众号会有测试信息)'];
                    $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【师傅信息通知】');
                    return view(null, ['list' => $results]);
                }
                $res = (new Recpeople())->where(['id' => $user['id']])->update(['openid' => $wxuser['id']]);
                if (!$res) {
                    $results = ['status' => 1, 'info' => '授权失败!'];
                    return view(null, ['list' => $results]);
                }
            }
        } catch (\Exception $e) {
            $results = ['status' => 1, 'info' => '授权失败,请重试'];
            return view(null, ['list' => $results]);
        }
        $results = ['status' => 0, 'info' => '公众号订单通知服务订阅成功!(授权成功公众号会有测试信息)'];
        $this->wechattest($wxuser['id'], '您好，您负责区域有新的订单', $message, '【师傅信息通知】');
        return view(null, ['list' => $results]);
    }

    //订单通知
    public function wechattest($touser = '', $first = '', $data, $remark = '')
    {
        $config = config('wechat2.');
        $app = Factory::officialAccount($config);
        $send_data = [
            'template_id' => 'FWkYSzgOUMUfxyKfmvY4MEtyTsOmTRDWtgBJBBu93W4', // 所需下发的订阅模板id
            'touser' => $touser,     // 接收者（用户）的 openid
            'miniprogram' => [
                'appid' => config('wechat.')['app_id'],
                'pagepath' => '/',
            ],
            'data' => [
                'first' => [
                    'value' => $first
                ],
                'keyword1' => [
                    'value' => $data[0] ?? ''
                ],
                'keyword2' => [
                    'value' =>  $data[1] ?? ''
                ],
                'keyword3' => [
                    'value' => $data[2] ?? ''
                ],
                'keyword4' => [
                    'value' =>  $data[3] ?? ''
                ],
                'keyword5' => [
                    'value' =>  $data[4] ?? ''
                ],
                'remark' => [
                    'value' => $remark
                ],
            ],
        ];
        $rm = $app->template_message->send($send_data);
    }

    public function convenclass()
    {
        $list = (new ConvenClass())->where('isshow', 1)->order(['sort' => 'desc'])->field('id,name')->select();
        $this->result($list, 0, '获取成功');
    }

    public function conven()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $classid = $this->request->get('classid/d', 0);
        $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
        $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
        $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
        // $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
        $where = [
            'type' => 1
        ];
        $where1 = [
            'type' => 2,
            'city' => $city['area_code'] ?? 0
        ];
        $where2 = [
            'type' => 3,
            'area' => $area['area_code'] ?? 0
        ];
        $where3 = [
            'type' => 4,
            'street' => $streetid ?? 0
        ];
        if (!empty($classid)) {
            $where['classid'] = $classid;
            $where1['classid'] = $classid;
            $where2['classid'] = $classid;
            $where3['classid'] = $classid;
        }
        $list = (new Conven())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->field('id,title,mobile,address,contents')->select();
        $this->result($list, 0, '获取成功');
    }

    public function others()
    {
        $name = $this->request->get('name', '');
        $result = (new Config())->where('name', $name)->find();
        $this->result($result, 0, '获取成功');
    }

    //回调结果
    public function callback()
    {

        $result = (new Wechat())->callback();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    //回调结果
    public function callback2()
    {
        $result = (new Wechat())->callback2();
        if ($result['msg'] == 'success') {
            return true;
        }
        return false;
    }

    public function business()
    {
        $businessid = $this->request->get('businessid/d', 0);
        $list = (new Business())->where('id', $businessid)->field('account,password,money,created', true)->find();
        $this->result($list, 0, '获取成功');
    }

    public function user_level()
    {
        $level = $this->request->get('level/d', 1);
        $result = (new UserLevel())->where('level', $level)->find();
        if ($result) {
            $result['coupon'] = json_decode($result['coupon'], true);
        }
        $this->result($result, 0, '获取成功');
    }

    public function oss()
    {
        // if (empty($_FILES['file'])) {
        //     $this->result([], 1, '参数错误');
        // }
        if ($this->request->isPost()) {
            $file = request()->file('file');
            $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
                ->move($path);
            if (!$info) {
                $this->result([], 1, $file->getError());
            } else {
                $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                $url = url($url, '', '', false);
                $url = "https://" . Env('app.api_url') . $url;
                $this->result($url, 0, '获取成功');
            }
        }
        // $file = $_FILES['file'];
        // $oss = new Oss();
        // $oss->setUploadType('ram');
        // $url = $oss->uploadPostFile($file, 'ming_user/' . date('Y-m-d'));
        // $this->result($url, 0, '获取成功');
        // $result = [];
        // try {
        //     $result = (new Oss())->getCredentials();
        //     $result['regionId'] = Env::get('aliyun.regionId');
        //     $result['bucket'] = Env::get('aliyun.bucket');
        //     $result['endpoint'] = Env::get('aliyun.endpoint');
        // } catch (\Exception $e) {
        //     $this->result([], 1, $e->getMessage());
        // }
        // $this->result($result, 0, '获取成功');
    }

    //高德接口
    public function getstreet()
    {
        $key = env('map.key');
        if ($this->request->isGet()) {
            $data = $this->request->get();
            $validate = new Validate([
                'lat' => 'require',
                'lng' => 'require',
            ], [
                'lat.require' => '纬度必须填写',
                'lng.require' => '经度必须填写',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $url = 'https://restapi.amap.com/v3/geocode/regeo';
            $res = api_curl($url, ['location' => $data['lng'] . ',' . $data['lat'], 'key' => $key, 'extensions' => 'all']);
            if ($res['status'] == 1) {
                if (empty($res['regeocode']['addressComponent'])) {
                    $this->result([], 1, '请求失败');
                }
                $results = $res['regeocode']['addressComponent'];
                $resuls = [
                    "adcode" => $results['adcode'] ?? 0,
                    "province" => $results['province'] ?? '',
                    "city" => $results['city'] ?? '',
                    "district" => $results['district'] ?? '',
                    "street" => 0,
                    "street_title" => $results['township'] ?? '',
                    'address' => $res['regeocode']['aois'][0]['name'] ?? '',
                    'formatted_address' => $res['regeocode']['formatted_address'] ?? ''
                ];
                $resuls['city'] = empty($resuls['city']) ? $resuls['province'] : $resuls['city'];
                $street_id = (new Region())
                    ->where(['level' => 4])
                    ->where('area_code', $resuls['adcode'])
                    ->where('name|remark', 'like', '%' . $resuls['street_title'] . '%')->find();
                //通过名字查找不到街道再通过编号查找
                if (empty($street_id['id'])) {
                    $street_id = (new Region())
                        ->where(['level' => 4])
                        ->where('area_code', $resuls['adcode'])
                        ->where('code', substr($results['towncode'], 0, 9))->find();
                }
                $resuls['street'] = $street_id['id'] ?? 0;
                $resuls['street_title'] = $street_id['name'] ?? $resuls['street_title'];
                $this->result($resuls, 0, '获取成功');
            } else {
                $this->result([], 1, '请求失败');
            }
        } else {
            $this->result([], 0, ['key' => $key]);
        }
    }

    public function street()
    {
        $areacode = $this->request->get('areacode/d', 0);
        $list = (new Region())->where('area_code', $areacode)->where(['level' => 4])->select();
        $this->result($list, 0, '获取成功');
    }

    public function addressjson()
    {
        $addressjsonredis = 'addressjsonredis';
        $haveaddress = Redis::get($addressjsonredis);
        if ($haveaddress) {
            $result = unserialize($haveaddress);
        } else {
            $region = (new Region())->field('name as label,area_code as value,id,parent_id,level')->where(['level' => [1, 2, 3]])->select();
            $resultson = [];
            $results = [];
            $result = [];
            foreach ($region as $regions) {
                if ($regions['level'] == 3) {
                    $resultson[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value']
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 2) {
                    $results[$regions['parent_id']][] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $resultson[$regions['id']] ?? []
                    ];
                }
            }
            foreach ($region as $regions) {
                if ($regions['level'] == 1) {
                    $result[] = [
                        'label' => $regions['label'],
                        'value' => $regions['value'],
                        'children' => $results[$regions['id']] ?? []
                    ];
                }
            }
            Redis::setex($addressjsonredis, 60 * 60 * 3, serialize($result));
        }
        return json($result);
    }

    public function getclass()
    {
        $list = (new PlatClass())->where('isshow', 1)->field('created,isshow', true)->order('sort desc');
        $getson = $this->request->get('getson/d', 2);
        $topid = $this->request->get('topid/d', 0);
        $type = $this->request->get('type/d', 1);
        if (!empty($topid)) {
            $list = $list->where('id', $topid);
        }
        $list = $list->where('type', $type);
        $list = $list->select();
        //获取下级子菜单
        $results = [];
        if ($type == 2) {
            $results[] = [
                'id' => 0,
                'type' => 2,
                'types' => 2,
                'ishot' => 2,
                'name' => '优选特产'
            ];
        }
        foreach ($list as $lists) {
            if ($getson == 1) {
                $lists['sons'] = (new PlatSons())->where('isshow', 1)->where('platclassid', $lists['id'])->field('created,platclassid,isshow', true)->order('sort desc')->select();
            }
            if ($type == 2) {
                $lists['types'] = 1;
            }
            $results[] = $lists;
        }
        $this->result($results, 0, '获取成功');
    }

    public function getgoodsclass()
    {
        $list = (new PlatClass())->where('isshow', 1)->where('ishot', 2)->where('type', 1)->field('created,sort,isshow', true)->order('sort desc')->select();
        $streetid = $this->request->get('streetid/d', 0);
        $type = $this->request->get('type/d', 1);
        $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
        $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
        $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
        foreach ($list as $lists) {
            //街道订单
            $where = [
                'b.status' => 1,
                'ba.street' => $street['id'] ?? 0,
                'ba.type' => 4,
                'g.classid' => $lists['id'],
                'g.isSale' => 1,
                'g.isdel' => 1,
                'g.type' => [1, 2],
            ];
            //区域订单
            $where1 = [
                'b.status' => 1,
                'ba.area' => $street['area_code'] ?? 0,
                'ba.type' => 3,
                'g.classid' => $lists['id'],
                'g.isSale' => 1,
                'g.isdel' => 1,
                'g.type' => [1, 2],
            ];
            //城市订单
            $where2 = [
                'b.status' => 1,
                'ba.city' => $city['area_code'] ?? 0,
                'ba.type' => 2,
                'g.classid' => $lists['id'],
                'g.isSale' => 1,
                'g.isdel' => 1,
                'g.type' => [1, 2],
            ];
            //城市订单
            $where3 = [
                'b.status' => 1,
                'ba.province' => 0,
                'ba.city' => 0,
                'ba.area' => 0,
                'ba.street' => 0,
                'ba.type' => 1,
                'g.classid' => $lists['id'],
                'g.isSale' => 1,
                'g.isdel' => 1,
                'g.type' => [1, 2],
            ];
            $goods = (new Goods())
                ->alias('g')
                ->join('business b', 'g.businessid= b.id')
                ->join('business_area ba', 'b.id= ba.businessid')
                ->whereOr(function ($query) use ($where) {
                    $query->where($where);
                })->whereOr(function ($query) use ($where1) {
                    $query->where($where1);
                })->whereOr(function ($query) use ($where2) {
                    $query->where($where2);
                })->whereOr(function ($query) use ($where3) {
                    $query->where($where3);
                })->field('g.id,g.type,g.title,g.images,g.recomm,g.goodspj')
                ->order(['b.sort' => 'desc', 'g.recomm' => 'desc', 'g.goodspj' => 'desc', 'g.sale' => 'desc'])
                ->limit(5)
                ->select();
            foreach ($goods as $good) {
                //查询所有评价
                $pj = (new Compent())->where('goodsid', $good['id'])->count();
                if ($pj > 0) {
                    $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
                } else {
                    $good['goodspj'] = 0;
                }
                $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
                $good['goods'] = (new GoodsSpec())->where('goodid', $good['id'])->order('is_default desc')->find();
                $good['images'] = json_decode($good['images'], true);
            }
            $lists['goods'] = $goods;
        }
        //获取下级子菜单
        $this->result($list, 0, '获取成功');
    }

    public function getsonclass()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new PlatSons())->where('isshow', 1)->where('platclassid', $id)->field('created,platclassid,sort,isshow', true)->order('sort desc')->select();
        $this->result($list, 0, '获取成功');
    }

    public function banner()
    {
        $streetid = $this->request->get('streetid/d', 0);
        $type = $this->request->get('type/d', 1);
        $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
        $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
        $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
        // $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
        $where = [
            'type' => 1,
            'types' => $type
        ];
        $where1 = [
            'type' => 2,
            'city' => $city['area_code'] ?? 0,
            'types' => $type
        ];
        $where2 = [
            'type' => 3,
            'area' => $area['area_code'] ?? 0,
            'types' => $type
        ];
        $where3 = [
            'type' => 4,
            'street' => $streetid ?? 0,
            'types' => $type
        ];
        $list = (new Banner())->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->field('id,title,url')->select();
        $this->result($list, 0, '获取成功');
    }

    public function goodslist()
    {
        $data = $this->request->get();
        //街道订单
        $where = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
        ];
        //区域订单
        $where1 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
        ];
        //城市订单
        $where2 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1]
        ];
        //全国订单
        $where3 = [
            ['b.status', '=', 1],
            ['g.isSale', '=',  1],
            ['g.isdel', '=', 1],
        ];
        //分类查询
        if (!empty($data['class'])) {
            $where[] = ['g.classid', '=', $data['class']];
            $where1[] = ['g.classid', '=', $data['class']];
            $where2[] = ['g.classid', '=', $data['class']];
            $where3[] = ['g.classid', '=', $data['class']];
        }
        //子分类查询
        if (!empty($data['sons'])) {
            $where[] = ['g.sonsid', '=', $data['sons']];
            $where1[] = ['g.sonsid', '=', $data['sons']];
            $where2[] = ['g.sonsid', '=', $data['sons']];
            $where3[] = ['g.sonsid', '=', $data['sons']];
        }
        //商家ID
        if (!empty($data['businessid'])) {
            $where[] = ['g.businessid', '=', $data['businessid']];
            $where1[] = ['g.businessid', '=', $data['businessid']];
            $where2[] = ['g.businessid', '=', $data['businessid']];
            $where3[] = ['g.businessid', '=', $data['businessid']];
        }
        if (!empty($data['title'])) {
            $where[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where1[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where2[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
            $where3[] = ['g.title|b.title|g.keywords', 'like', '%' . $data['title'] . '%'];
        }
        $list = (new Goods())
            ->alias('g')
            ->distinct(true)
            ->join('business b', 'g.businessid= b.id');
        if (!empty($data['streetid'])) {
            if (!empty($data['type']) && $data['type'] == 4) {
            } else {
                $list =  $list->join('business_area ba', 'b.id= ba.businessid');
                $street = (new Region())->where(['id' => $data['streetid'], 'level' => 4])->find();
                $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
                $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
                $where[] = ['ba.street', '=', $street['id'] ?? 0];
                $where[] = ['ba.type', '=',  4];
                $where1[] = ['ba.area', '=', $street['area_code'] ?? 0];
                $where1[] = ['ba.type', '=',  3];
                $where2[] = ['ba.city', '=', $city['area_code'] ?? 0];
                $where2[] = ['ba.type', '=',  2];
                $where3[] = ['ba.type', '=',  1];
            }
        }
        if (empty($data['type']) || $data['type'] == 1) {
            $where[] = ['g.type', 'IN',  [1, 2]];
            $where1[] = ['g.type', 'IN',  [1, 2]];
            $where2[] = ['g.type', 'IN',  [1, 2]];
            $where3[] = ['g.type', 'IN',  [1, 2]];
        } elseif ($data['type'] == 2) {
            $where[] = ['g.type', 'IN',  [3]];
            $where1[] = ['g.type', 'IN',  [3]];
            $where2[] = ['g.type', 'IN',  [3]];
            $where3[] = ['g.type', 'IN',  [3]];
        } elseif ($data['type'] == 3) {
            $where[] = ['g.type', 'IN',  [1, 2, 3, 4]];
            $where1[] = ['g.type', 'IN',  [1, 2, 3, 4]];
            $where2[] = ['g.type', 'IN',  [1, 2, 3, 4]];
            $where3[] = ['g.type', 'IN',  [1, 2, 3, 4]];
        } elseif ($data['type'] == 4) {
            $where[] = ['g.type', 'IN',  [4]];
            $where1[] = ['g.type', 'IN',  [4]];
            $where2[] = ['g.type', 'IN',  [4]];
            $where3[] = ['g.type', 'IN',  [4]];
        } elseif ($data['type'] == 5) {
            // $where[] = ['g.type', 'IN',  [3]];
            // $where1[] = ['g.type', 'IN',  [3]];
            // $where2[] = ['g.type', 'IN',  [3]];
            // $where3[] = ['g.type', 'IN',  [3]];
            $where[] = ['g.type', 'IN',  [3, 4]];
            $where1[] = ['g.type', 'IN',  [3, 4]];
            $where2[] = ['g.type', 'IN',  [3, 4]];
            $where3[] = ['g.type', 'IN',  [3, 4]];
        }
        $list = $list->whereOr(function ($query) use ($where) {
            $query->where($where);
        })->whereOr(function ($query) use ($where1) {
            $query->where($where1);
        })->whereOr(function ($query) use ($where2) {
            $query->where($where2);
        })->whereOr(function ($query) use ($where3) {
            $query->where($where3);
        })->field('g.id,g.title,g.images,g.recomm,g.descs,g.sale,g.goodspj,b.id as businessid,b.title as btitle');
        //排序
        $data['sort'] = $data['sort'] ?? 0;
        switch ($data['sort']) {
            case '1':
                $list = $list->order(['g.sale' => 'desc']);
                break;
            case '3':
                if (!empty($data['type']) && $data['type'] == 5) {
                    $list = $list->where(['g.recomm' => '2']);
                } else {
                    $list = $list->order(['g.recomm' => 'desc']);
                }
                break;
            default:
                $list = $list->order(['g.goodspj' => 'desc', 'g.sale' => 'desc']);
                break;
        }
        $list = $list->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $good) {
            //查询所有评价
            $pj = (new Compent())->where('goodsid', $good['id'])->count();
            if ($pj > 0) {
                $good['goodspj'] = floor($good['goodspj'] * 10000 / $pj) / 100;
            } else {
                $good['goodspj'] = 0;
            }
            $good['goodspj'] = $good['goodspj'] > 100 ? 100 : $good['goodspj'];
            $good['images'] = json_decode($good['images'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($list, 0, '获取成功');
    }

    public function goodsdetail()
    {
        $goodsid = $this->request->get('goodsid/d', 0);
        $streetid = $this->request->get('streetid/d', 0);
        $good = (new Goods())->field('created,classid,sonsid', true)->where(['isSale' => 1, 'isdel' => 1])->where('id', $goodsid)->find();
        if ($good) {
            if ($good['type'] == 4) {
                $good['canfw'] = 1;
            } else {
                $street = (new Region())->where(['id' => $streetid, 'level' => 4])->find();
                $area = (new Region())->where(['area_code' => $street['area_code'], 'level' => 3])->find();
                $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
                $where = ['businessid' => $good['businessid'], 'type' => 1];
                $where1 = ['businessid' => $good['businessid'], 'type' => 2, 'city' => $city['area_code'] ?? 0];
                $where2 = ['businessid' => $good['businessid'], 'type' => 3, 'area' => $area['area_code'] ?? 0];
                $where3 = ['businessid' => $good['businessid'], 'type' => 4, 'street' => $streetid ?? 0];
                $businessarea = (new BusinessArea())->whereOr(function ($query) use ($where) {
                    $query->where($where);
                })->whereOr(function ($query) use ($where1) {
                    $query->where($where1);
                })->whereOr(function ($query) use ($where2) {
                    $query->where($where2);
                })->whereOr(function ($query) use ($where3) {
                    $query->where($where3);
                })->find();
                $good['canfw'] = 0;
                if (!empty($businessarea)) {
                    $good['canfw'] = 1;
                }
            }
            $business = (new Business())->where(['id' => $good['businessid']])->find();
            if (empty($business) || $business['status'] != 1 || $business['shows'] != 1) {
                $good['canfw'] = 0;
            }
            $fwtime = $business['fwtime'] ?? '00:00 - 24:00';
            $fwtime = explode('-', $fwtime);
            $good['fwtime'] = $fwtime;
            $good['mobile'] = $business['mobile'] ?? '';
            $start = $fwtime[0] ?? '00:00';
            $end = $fwtime[1] ?? '22:00';
            //最早时间计算
            $zuizao = date('H', time() + 1800 + $good['times'] * 60) . ':00';
            //如果超越了营业时间可预约明天
            if (strtotime($zuizao) > strtotime($end)) {
                $zuizao = date('Y-m-d ', time() + 86400) . $start;
            } else {
                $zuizao = date('Y-m-d ') . $zuizao;
            }
            $good['business_name'] = $business['title'] ?? '';
            $good['zuizao'] = $zuizao;
            $good['images'] = json_decode($good['images'], true);
            $good['parpam'] = json_decode($good['parpam'], true);
            $good['goodspec'] = (new GoodsSpec())->field('id,price,name,stock,unmit')->where(['isdel' => 1, 'goodid' => $good['id']])->order('is_default desc')->select();
        }
        $this->result($good, 0, '获取成功');
    }
}
